package com.wzb.mybatisplus.bitaction.electrumaction.five;

import com.wzb.mybatisplus.bitaction.electrumaction.one.BitcoinKeyConverter;
import com.wzb.mybatisplus.bitaction.electrumaction.one.BlockchainBalanceChecker;
import com.wzb.mybatisplus.bitaction.electrumaction.one.KeyPair;
import com.wzb.mybatisplus.bitaction.electrumaction.three.SendEmailToQQ;
import com.wzb.mybatisplus.entity.Bituse;
import org.bitcoinj.core.*;
import org.bitcoinj.params.MainNetParams;
import org.bouncycastle.jce.ECNamedCurveTable;
import org.bouncycastle.jce.spec.ECNamedCurveParameterSpec;
import org.bouncycastle.math.ec.ECPoint;
import org.json.JSONObject;

import java.security.MessageDigest;
import java.security.SecureRandom;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class WIFPrivateKeyGenerator {

    private static final String BASE58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";

    /**
     * Base58编码
     */
    public static String base58Encode(byte[] input) {
        BigInteger value = new BigInteger(1, input);
        StringBuilder sb = new StringBuilder();

        while (value.compareTo(BigInteger.ZERO) > 0) {
            BigInteger[] divmod = value.divideAndRemainder(BigInteger.valueOf(58));
            sb.insert(0, BASE58.charAt(divmod[1].intValue()));
            value = divmod[0];
        }

        // 处理前导0
        for (byte b : input) {
            if (b == 0) {
                sb.insert(0, '1');
            } else {
                break;
            }
        }

        return sb.toString();
    }

    /**
     * 生成WIF格式私钥
     */
    public static String generateWIFPrivateKey(boolean compressed,BigInteger num) {
        try {
            SecureRandom random;
            if (num == null) {
                random = new SecureRandom();
            }else {
                 random = new SecureRandom(num.toByteArray());
            }
            byte[] privateKey = new byte[32];
            random.nextBytes(privateKey);

            // 版本号 0x80 + 私钥
            byte[] versionedKey = new byte[compressed ? 34 : 33];
            versionedKey[0] = (byte) 0x80; // 比特币主网版本号
            System.arraycopy(privateKey, 0, versionedKey, 1, 32);

            if (compressed) {
                versionedKey[33] = 0x01; // 压缩标志
            }

            // 计算校验和
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            byte[] hash1 = md.digest(versionedKey);
            byte[] hash2 = md.digest(hash1);

            // 添加校验和
            byte[] result = new byte[versionedKey.length + 4];
            System.arraycopy(versionedKey, 0, result, 0, versionedKey.length);
            System.arraycopy(hash2, 0, result, versionedKey.length, 4);

            return base58Encode(result);

        } catch (Exception e) {
            throw new RuntimeException("生成WIF私钥失败", e);
        }
    }

    public static void main(String[] args) {
        Set<String> addresses = new HashSet<>();
        Set<String> addressesSys = new HashSet<>();

//        for (int i = 1; i <= 10000000; i++) {
            // 生成未压缩的WIF私钥（以5开头）
            String wifUncompressed = generateWIFPrivateKey(false,new BigInteger("26"));
//            System.out.println("未压缩WIF私钥 (5开头): " + wifUncompressed);

            // 生成压缩的WIF私钥（以K或L开头）
            String wifCompressed = generateWIFPrivateKey(true,new BigInteger("26"));
//            System.out.println("压缩WIF私钥 (K/L开头): " + wifCompressed);


            // 私钥转公钥
//            String wifPrivateKey = privateKey.getWIFCompressed();

            //K开头
            KeyPair wifKeyPair = null;
            try {
                wifKeyPair = BitcoinKeyConverter.generateFromWIF(wifCompressed);
            } catch (Exception e) {

            }
            String addressk = wifKeyPair.getLegacyAddress(); // 比特币创始区块地址公钥地址
            addresses.add(addressk);
            addressesSys.add(wifCompressed);

            // 5开头
            try {

                NetworkParameters params = MainNetParams.get();

                DumpedPrivateKey dumpedPrivateKey = DumpedPrivateKey.fromBase58(params, wifUncompressed);
                ECKey ecKey = dumpedPrivateKey.getKey();


                byte[] publicKey = ecKey.getPubKey();
//                Address address5 = ecKey.toAddress(params);
                LegacyAddress address5 = LegacyAddress.fromKey(params, ecKey);
                addresses.add(address5.toString());
                addressesSys.add(wifUncompressed);

            } catch (Exception e) {
//                e.printStackTrace();
            }



//            addresses.add(bitcoinAddress);
//            addressesSys.add(wifUncompressed);

            List<String> asList = new ArrayList<>(addresses);

            if (addresses.size() >= 1) {
                List<String> list = new ArrayList<>();
                list.addAll(addresses);
                // 批量调用比特币
                String result = BlockchainBalanceChecker.getBalanceForAddresses(list);
                for (; result == null; ) {
//                    Thread.sleep(1000);
//                    flag++;
//                    System.out.println("=======调用比特币地址返回空，走进死循环中了======="+flag);
                    result = BlockchainBalanceChecker.getBalanceForAddresses(list);
                }
//                String addressString = String.join("|", addresses);
//                System.out.println(addressString);
//                System.out.println("============");
//                System.out.println(addressesSys);
                JSONObject jsonResponse = new JSONObject(result);

                for (String address : asList) {
                    JSONObject addressInfo = jsonResponse.getJSONObject(address);
//                    System.out.println(address+":    "+addressInfo);
                    Long maney = addressInfo.getLong("final_balance");
                    long total_received = addressInfo.getLong("total_received");
                    long jiaoyiliang = addressInfo.getLong("n_tx");
                    if (maney > 0 || jiaoyiliang > 0 || total_received > 0) {
                        System.out.println("=======金额======" + maney + "私钥：" + addressesSys);
//                        conutsum++;
                        Bituse bituse = new Bituse();
                        List<String> listSys = new ArrayList<>();
                        listSys.addAll(addressesSys);
//                        bituse.setWifsy(listSys);
//                        bituse.setMask(maney + "");
//                        bituseMapper.insert(bituse);
                        if (maney > 0) {
                            SendEmailToQQ sendEmailToQQ = new SendEmailToQQ();
                            sendEmailToQQ.sendEmail("2267457055@qq.com", "金额：" + maney + "   " + addressesSys.toString());

//                            for(String s : addressesSys){
//                                fileUtils.writeFile( s+"\n",path);
//                            }
                            System.out.println();

                        }

                    }


                }
                addresses.clear();
                addressesSys.clear();
//            }

        }



























    }
}